package com.erp.erp_ui.WjInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.WjInfo.WjInfoEntity;
import com.erp.erp_entitys.WjInfo.WjInfoExample;
import com.erp.erp_entitys.WjInfo.WjInfoVoEntity;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.WjCatalog.IWjCatalogService;
import com.erp.erp_servers.WjInfo.IWjInfoService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.*;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import static com.erp.utils.DateUtils.DATE_TIME_PATTERN;

/**
 * @ClassName WjInfoControl
 * @Description 文件信息
 * @Author songjizhen
 * @Date 2020-06-30 21:41
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "wjinfo")
public class WjInfoControl extends Base {

    @Autowired
    IWjInfoService  wjInfoService;
    @Autowired
    IWjCatalogService wjCatalogService;
    @Autowired
    IFtpService ftpService;
    // ftp客户端
    private FTPClient ftpClient = new FTPClient();
    /**
     * 文件
     * @param
     * @return
     */
    @RequestMapping(value = "selectByPage")
    @ResponseBody
    public R<List<WjInfoVoEntity>> selectByPage(String wjCatalogCode, String name){
        try{
           /* WjInfoExample example=new WjInfoExample();
            WjInfoExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike("%"+name+"%");
*/
           /* WjCatalogExample example2=new WjCatalogExample();
            WjCatalogExample.Criteria criteria1 = example2.createCriteria();
            criteria1.andNameLike("%"+wjCatalogCode+"%");
            List<WjCatalogEntity> wjCatalogEntities = wjCatalogService.selectByExample(example2);

            List<String> list=new ArrayList<>();
            for(int i=0;i<wjCatalogEntities.size();i++){
                list.add(wjCatalogEntities.get(i).getCode());
            }*/
           // criteria.andWjCatalogCodeIn(list);
            if(wjCatalogCode.equals("公司文件")) wjCatalogCode="1";
            WjInfoEntity we=new WjInfoEntity();
            we.setName(name);
            we.setWjCatalogCode(wjCatalogCode);
            List<WjInfoVoEntity> wjInfoEntities = wjInfoService.selectByName2(we);

            R<List<WjInfoVoEntity>> build = R.build(wjInfoEntities);
            Integer code = build.getCode();
            Long count = build.getCount();
            Integer status = build.getStatus();
            Long total = build.getTotal();

            List<WjInfoVoEntity> list=new ArrayList<>();
            for(int i=0;i<wjInfoEntities.size();i++){
                WjInfoEntity we1 = wjInfoEntities.get(i);
                String obj = DateUtils.format(we1.getUptime(), DATE_TIME_PATTERN);
               // wjInfoVoEntity.setUtime(obj);
                WjInfoVoEntity vo=new WjInfoVoEntity();
                vo.setUtime(obj);
                vo.setId(we1.getId());
                vo.setName(we1.getName());
                vo.setPath(we1.getPath());
                vo.setUpuser(we1.getUpuser());
                vo.setWjCatalogCode(we1.getWjCatalogCode());
                list.add(vo);
            }
            R<List<WjInfoVoEntity>> build1 = R.build(list);
            build1.setStatus(status);
            build1.setCount(count);
            build1.setTotal(total);
            build1.setCode(code);
            return build1;
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "delByid",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> delByid(Integer id){
        try{
            WjInfoEntity we = wjInfoService.selectByPrimaryKey(id);
            String wjCatalogCode = we.getWjCatalogCode();
            int num=0;
            if(wjCatalogCode.equals("4")){
                WjInfoEntity record=new WjInfoEntity();
                record.setId(id);
                record.setWjCatalogCode("5");
                num=wjInfoService.updateByPrimaryKeySelective(record);
            }else if(wjCatalogCode.equals("5")){
                num = wjInfoService.deleteByPrimaryKey(id);
            }else{
                WjInfoEntity record=new WjInfoEntity();
                record.setId(id);
                record.setWjCatalogCode("4");
                num=wjInfoService.updateByPrimaryKeySelective(record);
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 恢复
     * @param ids
     * @return
     */
    @RequestMapping(value = "hf",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> hf(String[] ids){
        try{
            WjInfoEntity record=new WjInfoEntity();
            int num=0;
            for(int  i=0; i<ids.length; i++){
                record.setWjCatalogCode("1");
                record.setId(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                num=wjInfoService.updateByPrimaryKeySelective(record);
            }

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 保存
     * @param files
     * @return
     */
    @RequestMapping(value = "savefile",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> savefile(String files,String wjCatalogCode,String name){
        try{
            wjCatalogCode=wjCatalogCode.replace("\"","");
            name=name.replace("\"","");
            JSONArray objs = (JSONArray) JSON.parse(files);
            int num=0;
            for(int i=0;i<objs.size();i++){
                JSONObject file = (JSONObject) objs.get(0);
                Object fileName = file.get("fileName");
                Object ftpPath = file.get("ftpPath");
                WjInfoEntity record=new WjInfoEntity();
                record.setWjCatalogCode(wjCatalogCode);
                record.setName(name);
                record.setPath(ftpPath.toString()+"/"+fileName.toString());
                record.setUptime(new Date());
                /////////判断文件是否存在////
                WjInfoExample example=new WjInfoExample();
                WjInfoExample.Criteria criteria = example.createCriteria();
                criteria.andWjCatalogCodeEqualTo(wjCatalogCode);
                criteria.andNameEqualTo(name);
                List<WjInfoEntity> wjInfoEntities = wjInfoService.selectByExample(example);
                if(wjInfoEntities.size()>0){
                    WjInfoEntity wjInfoEntity = wjInfoEntities.get(0);
                    wjInfoEntity.setPath(record.getPath());
                    num=wjInfoService.updateByPrimaryKey(wjInfoEntity);
                }else{
                    num=wjInfoService.insertSelective(record);

                }

                ////////////

               // System.out.println(o.toString());

                //.get("fileName");
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 下载
     * @param path
     */
    @RequestMapping(value = "downloadfile",method = RequestMethod.POST)
    @ResponseBody
    public void downloadfile(String path, HttpServletResponse response)throws Exception{
        Properties properties = PropertiesUtils.loadProperties("ftp");
       String pathname=path.substring(1,path.lastIndexOf("/")+1).replace("\"","");
        String filename=path.substring(path.lastIndexOf("/")+1).replace("\"","");
        String localpath= properties.getProperty("downloadpath");;

        ftpService.downloadFile(pathname,filename,localpath);

    }

    /**
     * 根据文件目录查询其下所有的文件名
     * @param wjCatalogCode
     * @return
     */
    @RequestMapping(value = "ispd")
    @ResponseBody
    public R<Integer> ispd(String wjCatalogCode,String name){
        try {
            WjInfoEntity record=new WjInfoEntity();
            record.setName(name);
            record.setWjCatalogCode(wjCatalogCode);
            int num = wjInfoService.distinctByName(record);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     *
     * @param filename
     * @return
     */
    @RequestMapping(value = "getFileName")
    @ResponseBody
    public R<String> getFileName(String filename){
        try {
            String name="";
           // String[] objs=filename.split(".");
            name=filename.substring(0,filename.indexOf("."))+"%"+filename.substring(filename.indexOf("."));

            int num = wjInfoService.queryFileCount(name);
            return R.build(filename.substring(0,filename.indexOf("."))+"("+(num+1)+")"+filename.substring(filename.indexOf(".")));
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    ////////////////////////////////////
    /**
     *
     * 功能：根据文件名称，下载文件流
     * @param filename 文件名
     * @return
     * @throws
     */
    @RequestMapping(value = "downloadfile2")
    @ResponseBody
    public void downloadfile2(String filename, HttpServletResponse response, HttpServletRequest request)throws Exception{
        FtpOperationUtil ftp=new FtpOperationUtil();
        ftp.download(filename,response, request);

    }

    /**
     * 根据供应商编码，查询其下文件
     * @param code
     * @return
     */
    @RequestMapping(value = "getFileByCataLogCode")
    @ResponseBody
    public R<List> getFileByCataLogCode(String code){
        WjInfoExample example=new WjInfoExample();
        WjInfoExample.Criteria criteria = example.createCriteria();
        criteria.andWjCatalogCodeEqualTo(code);
        List<WjInfoEntity> selectByExample=wjInfoService.selectByExample( example);
        List<String> list=new ArrayList<>();
        for(WjInfoEntity we:selectByExample){
            String path=we.getPath();
            //ftp/downloadimg?pathname=/upload/4/admin/1616945273565/customerlogo&filename=1616945273565.jpg
           // /upload/4/admin/1616945173006/productwj/1616945173007.docx
            String pathname=path.substring(0,path.lastIndexOf("/"));
            String filename=path.substring(path.lastIndexOf("/")+1);
            String filePath="ftp/downloadimg?pathname="+pathname+"&filename="+filename;
            list.add(filePath);
        }
        return R.build(list);
    }

}
